/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.mahasen.client.gui;

import java.rmi.RemoteException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

import org.mahasen.authentication.ClientLogin;
import org.mahasen.authentication.ClientLoginData;
import org.mahasen.client.AuthenticationExceptionException;
import org.mahasen.configuration.ClientConfiguration;


public class Login extends javax.swing.JFrame {

    ClientConfiguration clientConfiguration = ClientConfiguration.getInstance();

    /**
     * Creates new form Login
     */
    public Login() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        hostIpLable = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        hostIpTextField = new javax.swing.JTextField();
        userNameTextField = new javax.swing.JTextField();
        clientLoginButton = new javax.swing.JButton();
        loginCancelButton = new javax.swing.JButton();
        passwordField = new javax.swing.JPasswordField();
        portTextField = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Client Login");
        setBackground(new java.awt.Color(16, 14, 14));

        hostIpLable.setText("Host IP :");

        jLabel2.setText("User Name :");

        jLabel3.setText("Password :");

        hostIpTextField.setText("10.8.99.");
        hostIpTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                hostIpTextFieldActionPerformed(evt);
            }
        });

        userNameTextField.setText("admin");

        clientLoginButton.setText("Login");
        clientLoginButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clientLoginButtonActionPerformed(evt);
            }
        });

        loginCancelButton.setText("Cancel");
        loginCancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loginCancelButtonActionPerformed(evt);
            }
        });

        passwordField.setText("admin");

        portTextField.setText("9443");

        jLabel4.setText("Port :");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(hostIpLable)
                                        .addComponent(jLabel3)
                                        .addComponent(jLabel2)
                                        .addComponent(jLabel4))
                                .addGap(67, 67, 67)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addGroup(layout.createSequentialGroup()
                                                .addComponent(clientLoginButton, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 49, Short.MAX_VALUE)
                                                .addComponent(loginCancelButton, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addComponent(passwordField, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 214, Short.MAX_VALUE)
                                        .addComponent(userNameTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 214, Short.MAX_VALUE)
                                        .addComponent(portTextField, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 214, Short.MAX_VALUE)
                                        .addComponent(hostIpTextField, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 214, Short.MAX_VALUE))
                                .addGap(27, 27, 27))
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addContainerGap(163, Short.MAX_VALUE)
                                .addComponent(clientLoginButton, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(175, 175, 175))
        );
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                                .addGap(47, 47, 47)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addGroup(layout.createSequentialGroup()
                                                .addGap(4, 4, 4)
                                                .addComponent(hostIpLable))
                                        .addGroup(layout.createSequentialGroup()
                                                .addComponent(hostIpTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addGap(18, 18, 18)
                                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                        .addComponent(portTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                        .addComponent(jLabel4))
                                                .addGap(18, 18, 18)
                                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                        .addComponent(userNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                        .addComponent(jLabel2))
                                                .addGap(18, 18, 18)
                                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                        .addComponent(passwordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                        .addComponent(jLabel3))
                                                .addGap(33, 33, 33)
                                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                        .addComponent(clientLoginButton)
                                                        .addComponent(loginCancelButton))))
                                .addContainerGap(43, Short.MAX_VALUE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width - 403) / 2, (screenSize.height - 331) / 2, 403, 331);
    }// </editor-fold>//GEN-END:initComponents

    private void clientLoginButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clientLoginButtonActionPerformed


        String hostIp = hostIpTextField.getText();
        String port = portTextField.getText();
        String userName = userNameTextField.getText();
        String passWord = passwordField.getText();
        if (!hostIp.equals("") && !port.equals("")
                && !userName.equals("") && !passWord.equals("")) {
            clientConfiguration.setHost(hostIp);
            clientConfiguration.setPort(port);
            clientConfiguration.setUserName(userName);
            clientConfiguration.setPassWord(passWord);
            String hostAndPort = clientConfiguration.getHost() + ":" + clientConfiguration.getPort();
            ClientLogin clientLogin = new ClientLogin();
            Boolean isLogged = false;

            System.setProperty("javax.net.ssl.trustStore", clientConfiguration.getTrustStorePath());
            System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon");
            System.setProperty("javax.net.ssl.trustStoreType", "JKS");
            try {
                ClientLoginData loginData = clientLogin.remoteLogin(hostAndPort, userName, passWord);
                isLogged = loginData.isLoggedIn();

                if (isLogged) {
                    this.dispose();

                    new MahasenClient(loginData).setVisible(true);
                } else {
                    JOptionPane.showMessageDialog(this, "Login Failed");
                    passwordField.setText("");
                }
                // TODO add your handling code here:
            } catch (AuthenticationExceptionException ex) {
                Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
            } catch (RemoteException ex) {
                Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            if (hostIp.equals("")) {
                JOptionPane.showMessageDialog(this, "Host IP is not set");
            } else if (port.equals("")) {
                JOptionPane.showMessageDialog(this, "PORT number is not set");
            } else if (userName.equals("")) {
                JOptionPane.showMessageDialog(this, "Please enter User Name");
            } else if (passWord.equals("")) {
                JOptionPane.showMessageDialog(this, "Please enter Password");
            } else {
                JOptionPane.showMessageDialog(this, "Download Repository is not set");
            }
        }
    }//GEN-LAST:event_clientLoginButtonActionPerformed

    private void loginCancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loginCancelButtonActionPerformed
        this.dispose();
        // TODO add your handling code here:
    }//GEN-LAST:event_loginCancelButtonActionPerformed

    private void hostIpTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_hostIpTextFieldActionPerformed
// TODO add your handling code here:
    }//GEN-LAST:event_hostIpTextFieldActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Login().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton clientLoginButton;
    private javax.swing.JLabel hostIpLable;
    private javax.swing.JTextField hostIpTextField;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JButton loginCancelButton;
    private javax.swing.JPasswordField passwordField;
    private javax.swing.JTextField portTextField;
    private javax.swing.JTextField userNameTextField;
    // End of variables declaration//GEN-END:variables
}
